<template>
  <div>
    <el-card>
      <el-form
        :model="form"
        status-icon
        :rules="rules"
        label-width="100px"
        class="login-container"
      >
        <h3>系统登录</h3>
        <el-form-item label="用户名" label-width="80px" prop="username">
          <el-input
            type="input"
            v-model="form.username"
            autocomplete="off"
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" label-width="80px" prop="password">
          <el-input
            type="password"
            v-model="form.password"
            autocomplete="off"
            placeholder="请输入密码"
          ></el-input
        ></el-form-item>

        <el-form-item>
          <el-button type="primary" @click="login" class="login-button"
            >登录</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
// import Mock from "mockjs";
import { mapMutations } from "vuex";
import { getMenu } from "../../api/data";
export default {
  data() {
    return {
      form: {
        username: "",
        password: "",
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, message: "用户名长度不能小于3位", trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
    };
  },
  methods: {
    ...mapMutations("user", ["setToken","setUsername"]),
    ...mapMutations("tab", ["addMenu", "setMenu", "clearMenu"]),
    login() {
      if (!this.form.username || !this.form.password) {
        return this.$message.error("用户名密码不能为空!");
      }
      getMenu(this.form).then(({ data: res }) => {
        if (res.code === 200) {
          this.clearMenu();
          this.setMenu(res.data.menu);
          this.setToken(res.data.token);
          this.addMenu(this.$router);
          this.setUsername(this.form.username)
          this.$router.push({ name: "home" });
          this.$message.success("登录成功");
        } else {
          return this.$message.error(res.data.message);
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.el-card {
  width: 450px;
  position: absolute;
  top: 30%;
  left: 50%;
  transform: translate(-50%, -50%);
  h3 {
    text-align: center;
  }
  .login-button {
    margin-left: 75px;
  }
}
</style>
